package service

import (
	"encoding/json"
	"fmt"
	"multimedia/utils"
	"net/http"
	"os"
	"path"
	"strconv"

	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	log "github.com/sirupsen/logrus"
)

// 查询用户信息
func (s *Srv) GetUserInfo(c *gin.Context) {
	userId := c.Query("userId")
	if userId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"code": -1, "msg": "用户标识为空"})
		return
	}
	useridInt, _ := strconv.ParseInt(userId, 10, 64)
	userInfo, err := s.mysql.GetUserInfo(useridInt)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": -1, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "", "data": utils.EncryptDataByAes(userInfo)})
}

// 修改用户昵称
func (s *Srv) EditUserNickname(c *gin.Context) {
	userIdStr := c.Query("userId")
	userId, _ := strconv.ParseInt(userIdStr, 10, 64)
	nickname := c.Query("nickname")
	res := s.mysql.UpdateUserNickname(nickname, userId)
	if res == 0 {
		c.JSON(http.StatusOK, gin.H{"code": utils.ModifyFail, "msg": "", "data": utils.EncryptDataByAes(false)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": utils.Success, "msg": "", "data": utils.EncryptDataByAes(res)})
}

// 头像上传方形
// 参数userid单独加密解密处理
func (s *Srv) AvatarUpload(c *gin.Context) {
	data := c.PostForm("data")
	res, err := utils.DecryptByAes(data)
	log.WithField("Func", "AvatarUpload").Infof("the url is:%v,the before decryption is:%s, the After decryption is %s", c.Request.URL, data, res)
	if err != nil {
		log.WithField("Func", "AvatarUpload").Warnf("DecryptByAes error", err.Error())
		type MAContentType struct {
			ErrStr string `json:"errstr"` // 错误码
		}
		pack := MAContentType{
			ErrStr: fmt.Sprintf("post DecryptByAes url:%v error  %s", c.Request.URL, err.Error()),
		}
		c.JSON(http.StatusBadRequest, pack)
		return
	}
	jsonData := make(map[string]string)
	err = json.Unmarshal(res, &jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": utils.ReqParamErr, "msg": "参数错误"})
		return
	}
	//_ = json.Unmarshal(data, &Confer)
	userIdStr := jsonData["userId"]
	if userIdStr == "" {
		c.JSON(http.StatusOK, gin.H{"code": utils.ReqParamErr, "msg": "参数错误"})
		return
	}
	userId, _ := strconv.ParseInt(userIdStr, 0, 64)
	headers, err := c.FormFile("file")
	if err != nil {
		log.WithField("Func", "AvatarUpload").Warnf("get file fail", err.Error())
		c.JSON(http.StatusOK, gin.H{"code": utils.FileUploadErr, "msg": "上传图片出错", "data": utils.EncryptDataByAes(false)})
		return
	}
	if headers.Size > 1024*1024*2 {
		c.JSON(http.StatusOK, gin.H{"code": utils.FileUploadErr, "msg": "上传图片过大", "data": utils.EncryptDataByAes(false)})
		return
	}
	ext := path.Ext(headers.Filename)
	allowExtMap := map[string]bool{
		".jpg":  true,
		".png":  true,
		".gif":  true,
		".jpeg": true,
	}
	if _, ok := allowExtMap[ext]; !ok {
		c.JSON(http.StatusOK, gin.H{"code": utils.FileUploadErr, "msg": "不支持的图片类型", "data": utils.EncryptDataByAes(false)})
		return
	}
	newFileName := uuid.NewV4().String() + ext
	path := path.Join("./avatar", userIdStr)
	dir := path + "/" + newFileName
	flag, _ := utils.PathExists(path)
	if !flag {
		err = os.MkdirAll(path, os.ModePerm)
		if err != nil {
			log.WithField("Func", "AvatarUpload").Errorf("mkdir folder fail.", err)
			c.JSON(http.StatusOK, gin.H{"code": utils.FileUploadErr, "msg": "", "data": utils.EncryptDataByAes(false)})
			return
		}
	}
	err = c.SaveUploadedFile(headers, dir)
	if err != nil {
		log.WithField("Func", "AvatarUpload").Errorf("file upload fail.", err)
		c.JSON(http.StatusOK, gin.H{"code": utils.FileUploadErr, "msg": "", "data": utils.EncryptDataByAes(false)})
		return
	}
	// 存储用户头像地址
	s.mysql.UpdateUserAvatar(dir, userId)
	m := map[string]string{
		"avatar": dir,
	}
	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "", "data": utils.EncryptDataByAes(m)})
}

// 上传头像、视频页面展示圆形头像
func (s *Srv) AvatarCircularUpload(c *gin.Context) {
	data := c.PostForm("data")
	res, err := utils.DecryptByAes(data)
	log.WithField("Func", "avatarCircularUpload").Infof("the url is:%v,the before decryption is:%s, the After decryption is %s", c.Request.URL, data, res)
	if err != nil {
		log.WithField("Func", "avatarCircularUpload").Warnf("DecryptByAes error", err.Error())
		type MAContentType struct {
			ErrStr string `json:"errstr"` // 错误码
		}
		pack := MAContentType{
			ErrStr: fmt.Sprintf("post DecryptByAes url:%v error  %s", c.Request.URL, err.Error()),
		}
		c.JSON(http.StatusBadRequest, pack)
		return
	}
	jsonData := make(map[string]string)
	err = json.Unmarshal(res, &jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": utils.ReqParamErr, "msg": "参数错误"})
		return
	}
	//_ = json.Unmarshal(data, &Confer)
	userIdStr := jsonData["userId"]
	if userIdStr == "" {
		c.JSON(http.StatusOK, gin.H{"code": utils.ReqParamErr, "msg": "参数错误"})
		return
	}
	userId, _ := strconv.ParseInt(userIdStr, 0, 64)
	headers, err := c.FormFile("file")
	if err != nil {
		log.WithField("Func", "avatarCircularUpload").Warnf("get file fail", err.Error())
		c.JSON(http.StatusOK, gin.H{"code": utils.FileUploadErr, "msg": "上传图片出错", "data": utils.EncryptDataByAes(false)})
		return
	}
	if headers.Size > 1024*1024*2 {
		c.JSON(http.StatusOK, gin.H{"code": utils.FileUploadErr, "msg": "上传图片过大", "data": utils.EncryptDataByAes(false)})
		return
	}
	ext := path.Ext(headers.Filename)
	allowExtMap := map[string]bool{
		".jpg":  true,
		".png":  true,
		".gif":  true,
		".jpeg": true,
	}
	if _, ok := allowExtMap[ext]; !ok {
		c.JSON(http.StatusOK, gin.H{"code": utils.FileUploadErr, "msg": "不支持的图片类型", "data": utils.EncryptDataByAes(false)})
		return
	}
	newFileName := uuid.NewV4().String() + ext
	path := path.Join("./avatar", userIdStr)
	dir := path + "/" + newFileName
	flag, _ := utils.PathExists(path)
	if !flag {
		err = os.MkdirAll(path, os.ModePerm)
		if err != nil {
			log.WithField("Func", "avatarCircularUpload").Errorf("mkdir folder fail.", err)
			c.JSON(http.StatusOK, gin.H{"code": utils.FileUploadErr, "msg": "", "data": utils.EncryptDataByAes(false)})
			return
		}
	}
	err = c.SaveUploadedFile(headers, dir)
	if err != nil {
		log.WithField("Func", "AvatarUpload").Errorf("file upload fail.", err)
		c.JSON(http.StatusOK, gin.H{"code": utils.FileUploadErr, "msg": "", "data": utils.EncryptDataByAes(false)})
		return
	}
	// 存储用户头像地址圆形头像
	s.mysql.UpdateUserAvatarCircular(dir, userId)
	m := map[string]string{
		"avatarCircular": dir,
	}
	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "", "data": utils.EncryptDataByAes(m)})
}

// 获取用户进房签名
func (s *Srv) GetUserSig(c *gin.Context) {
	userId := c.Query("userId")
	userSig := s.TLSSig.GenUserSig(userId, 180*86400)
	m := map[string]string{
		"userSig": userSig,
	}
	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "", "data": utils.EncryptDataByAes(m)})
}
